const fs = require('fs');
const path = require('path');
const yaml = require('yaml');
const { program } = require('commander');
const Table = require('cli-table3');

// 配置命令行参数
program
  .option('-n, --name <name>', '通过项目名查找')
  .option('-m, --manufacture <manufacture>', '通过厂商查找')
  .option('-v, --version <version>', '通过版本号查找')
  .option('-p, --ispassed <ispassed>', '是否通过，1为true，0为false');

// 解析命令行参数
program.parse(process.argv);
const options = program.opts();

// 读取记录文件
const yamlPath = path.join(__dirname, 'compresslist.yaml');
let records = [];

try {
  if (fs.existsSync(yamlPath)) {
    const yamlContent = fs.readFileSync(yamlPath, 'utf8');
    records = yaml.parse(yamlContent) || [];
  } else {
    console.log('没有找到记录文件，可能还没有任何记录。');
    process.exit(0);
  }
} catch (error) {
  console.error('读取记录时出错：', error.message);
  process.exit(1);
}

// 根据参数过滤记录
let filteredRecords = records;

if (options.name) {
  filteredRecords = filteredRecords.filter(record => 
    record.name.toLowerCase().includes(options.name.toLowerCase())
  );
}

if (options.manufacture) {
  filteredRecords = filteredRecords.filter(record => 
    record.manufacture === options.manufacture
  );
}

if (options.version) {
  filteredRecords = filteredRecords.filter(record => 
    record.version === options.version
  );
}

if (options.ispassed !== undefined) {
  const isPassed = options.ispassed === '1';
  filteredRecords = filteredRecords.filter(record => 
    record.ispassed === isPassed
  );
}

// 显示结果
if (filteredRecords.length === 0) {
  console.log('没有找到匹配的记录。');
  process.exit(0);
}

// 创建表格（新增项目说明列）
const table = new Table({
  head: [
    '项目名称', 
    '厂商', 
    '版本号', 
    '添加时间', 
    '更改前体积', 
    '更改后体积', 
    '体积限制', 
    '是否通过',
    '项目说明' // 新增列
  ],
  colWidths: [20, 10, 10, 20, 12, 12, 12, 10, 30] // 调整列宽
});

// 添加记录到表格（包含comment）
filteredRecords.forEach(record => {
  table.push([
    record.name,
    record.manufacture,
    record.version,
    new Date(record.addtime).toLocaleString(),
    record.before,
    record.after,
    record.limit,
    record.ispassed ? '是' : '否',
    record.comment || '' // 显示comment，默认空
  ]);
});

// 显示表格
console.log(table.toString());

// 新增：输出筛选后的记录总数
console.log(`\n查询到的匹配记录总数：${filteredRecords.length} 条`);